package script;

import java.util.ArrayList;

import define.Common;
import define.Keyword;

public class StringHander 
{
	StringBuffer m_string;
	
	public StringHander(StringBuffer buffer)
	{
		m_string = buffer;
	}
	
	public StringBuffer replace(String old, String newStr)
	{
		int start = 0;
		int index = find(old, 0);
		int len = old.length();
		ArrayList<String> list = new ArrayList<>();
		while(index != -1)
		{
			if(index > start)
			{
				list.add(m_string.substring(start, index));
			}
			list.add(null);
			start = index + len;
			index = find(old, start);
		}
		list.add(m_string.substring(start));
		StringBuffer out = new StringBuffer("");
		for(String temp: list)
		{
			
			out.append(temp == null? newStr: temp);
		}
		return out;
	}
	
	public ArrayList<String> split(String des)
	{
		int start = 0;
		int index = find(des, 0);
		int len = des.length();
		ArrayList<String> list = new ArrayList<>();
		while(index != -1)
		{
			if(index > start)
			{
				list.add(m_string.substring(start, index));
			}
			else
			{
				list.add("");
			}
			start = index + len;
			index = find(des, start);
		}
		list.add(m_string.substring(start));
		return list;
	}
	
	public StringBuffer sub(String start, String end)
	{
		boolean isText = start.charAt(0) == Keyword.E_CELL_STRING_KEY.getChar();
		Integer s = null;
		Integer e = null;
		StringBuffer out = new StringBuffer("");
		if(isText)
		{
			s = find(start.substring(1), 0);
			if(s == -1)
			{
				return out;
			}
		}
		else
		{
			s = Common.isInt(start);
			if(s == null)
			{
				return out;
			}
		}
		isText = end.charAt(0) == Keyword.E_CELL_STRING_KEY.getChar();
		if(isText)
		{
			e = find(end.substring(1), 0);
			if(e == -1)
			{
				return out;
			}
			e += end.length() - 2;
		}
		else
		{
			e = Common.isInt(end);
			if(e == null)
			{
				return out;
			}
		}
		if(s < 0)
		{
			s = m_string.length() + s;
		}
		if(e < 0)
		{
			e = m_string.length() + e;
		}
		if(s > e)
		{
			return out;
		}
		if(e >= m_string.length())
		{
			out.append(m_string.substring(s));
			return out;
		}
		out.append(m_string.substring(s, e + 1));
		return out;
	}
	
	private int find(String des, int start)
	{
		return m_string.indexOf(des, start);
	}
}
